package org.jeecg.modules.yks.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Dictionary;

public class HttpConnectUtil {

    public static StringBuilder getData(Dictionary apiConfig) {
        String credentials = apiConfig.get("username") + ":" + apiConfig.get("password");
        String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());

        String authorizationHeader = "Basic " + encodedCredentials;
        StringBuilder response = null;
        try {
            URL url = new URL(apiConfig.get("hostUrl") + ":" + apiConfig.get("port") + apiConfig.get("api"));
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", authorizationHeader); // 替换为你的emqx管理API的用户名和密码

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                response = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                System.out.println(response.toString());
            } else {
                System.out.println("HTTP request failed with response code: " + responseCode);
            }
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
    public static StringBuilder postData() {

        return null;
    }
}
